package com.nowcoder.community.service;

import com.nowcoder.community.mapper.LoginTicketMapper;
import com.nowcoder.community.mapper.UserMapper;
import com.nowcoder.community.pojo.LoginTicket;
import com.nowcoder.community.pojo.User;
import com.nowcoder.community.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service("userService")
public class UserServiceImpl implements UserService, CommunityConstant{

    @Autowired
    @Qualifier("userMapper")
    private UserMapper userMapper;

//    @Autowired
//    @Qualifier("loginTicketMapper")
//    private LoginTicketMapper loginTicketMapper;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Value("${community.path.domain}")
    private String domain;//域名

    @Value("${server.servlet.context-path}")
    private String contextPath;//项目名

    @Autowired
    private HostHolder hostHolder;

    @Override
    public User findUserById(int userId){

        User user = getCache(userId);

        if (user == null){
            user = initCache(userId);
        }
        return user;
    }

    @Override
    public Map<String, Object> register(User user){
        HashMap<String, Object> map = new HashMap<>();

        if (user == null){
            throw new IllegalArgumentException("参数不能为空！");
        }

        if (StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg", "用户名不能为空！");
            return map;//此时map不为空容器
        }

        if (StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg", "密码不能为空！");
            return map;
        }

        if (StringUtils.isBlank(user.getEmail())){
            map.put("emailMsg", "邮箱不能为空");
            return map;
        }


        //验证账号
        User u = userMapper.getUserByName(user.getUsername());
        if (u != null){
            map.put("usernameMsg", "该账号已存在！");
            return map;
        }

        //验证邮箱
        u = userMapper.getUserByEmail(user.getEmail());
        if (u != null){
            map.put("emailMsg", "该邮箱已被注册！");
            return map;
        }

        //注册用户
        //设置设置加密信息（盐）（UUID随机生成取前5位）
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));

        //密码=用户输入的密码+随机生成的UUID的前5位
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));

        //设置用户类型（0表示普通用户）
        user.setType(0);

        //设置用户当前状态
        user.setStatus(0);

        //设置激活码
        user.setActivationCode(CommunityUtil.generateUUID());

        //设置用户头像地址http://images.nowcoder.com/head/1t.png
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));

        //设置用户创建日期
        user.setCreateTime(new Date());

        //添加用户
        userMapper.addUser(user);

        //激活邮件
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        //http://localhost:8080/community/activation/101/code
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);

        //发送邮件到指定页面 指定的页面的位置+该页面发送的内容（包含邮箱和页面URL）
        String content = templateEngine.process("/mail/activation", context);
        
        //发送邮件
        mailClient.sendMail(user.getEmail(), "激活账号", content);

        return map;//如果注册成功，那么这个map就为空容器
    }

    /**
     * 当前用户状态为1，已经激活成功，无需激活
     * 当前用户状态为0，说明用户未激活，激活后更新用户状态为1，表明激活成功
     * 不满足上述条件，激活失败
     * */
    @Override
    public int activation(int userId, String code){
        User user = userMapper.getUserById(userId);
        if (user.getStatus() == 1){
            return ACTIVATION_REPEAT;
        }else if (user.getActivationCode().equals(code)){
            userMapper.updateUserStatus(userId, 1);
            clearCache(userId);
            return ACTIVATION_SUCCESS;
        }else {
            return ACTIVATION_FAILURE;
        }
    }


    /**
     * 方法中有添加评论和更新评论数量两个操作，这两个操作是同步的，
     * 要么同时成功，要么同时失败，所以要添加事务
     * @return map为空容器时，用户满足登录要求
     */
//    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    @Override
    public Map<String, Object> login(String username, String password, int expireSeconds){
        Map<String, Object> map = new HashMap<>();

        //空值处理
        if (StringUtils.isBlank(username)){
            map.put("usernameMsg", "账号不能为空！");
            return map;
        }

        if (StringUtils.isBlank(password)){
            map.put("passwordMsg", "密码不能为空！");
            return map;
        }

        User user = userMapper.getUserByName(username);

        //验证用户
        if (user == null){
            map.put("usernameMsg", "该账号不存在！");
            return map;
        }

        //验证状态
        if (user.getStatus() == 0){
            map.put("usernameMsg", "该账号未激活！");
            return map;
        }

        //验证密码
        password = CommunityUtil.md5(password + user.getSalt());
        if (!password.equals(user.getPassword())){
            map.put("passwordMsg", "密码不正确！");
            return map;
        }

        //生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        //expireSeconds * 1000已经超过int型范围，需要转化成long型
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expireSeconds * 1000L));//单位是ms

//        System.out.println("过期时间：" + loginTicket.getExpired());
//        loginTicketMapper.insertLoginTicket(loginTicket);

        //将登录凭证实例添加到Redis中
        String ticketRedisKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(ticketRedisKey, loginTicket);


        //将用户凭证存放到容器中以便发送给用户
        map.put("ticket", loginTicket.getTicket());
        return map;
    }

    @Override
    public LoginTicket findLoginTicket(String ticket) {
//        return loginTicketMapper.selectByTicket(ticket);
        String ticketRedisKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket)redisTemplate.opsForValue().get(ticketRedisKey);
    }

    @Override
    public void exit(String ticket){
//        loginTicketMapper.updateStatus(ticket, 1);
        String ticketRedisKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket)redisTemplate.opsForValue().get(ticketRedisKey);
        loginTicket.setStatus(1);//1表示删除凭证（当前用户退出登录后，要删除凭证）
        redisTemplate.opsForValue().set(ticketRedisKey, loginTicket);
    }

    @Override
    public int updateHeader(int userId, String headerUrl) {

        int updateResult = userMapper.updateUserHeader(userId, headerUrl);

        clearCache(userId);

        return updateResult;
    }

    @Override
    public Map<String, Object> updatePassword(String oldPassword, String newPassword, String rePassword) {

        HashMap<String, Object> map = new HashMap<>();

        //获取当前线程用户
        User user = hostHolder.getUser();

        if (oldPassword == null){
            map.put("oldPwdMsg", "原密码不能为空！");
            return map;
        }

        if (newPassword == null){
            map.put("newPwdMsg", "新密码不能为空！");
            return map;
        }

        oldPassword = CommunityUtil.md5(oldPassword + user.getSalt());

        if ( !(oldPassword.equals(user.getPassword())) ){
            map.put("oldPwdMsg", "原密码错误！");
            return map;
        }

        if ( !(newPassword.equals(rePassword)) ){
            map.put("pwdMsgDiff", "两次输入的密码不一致！");
            return map;
        }

        newPassword = CommunityUtil.md5(newPassword + user.getSalt());

        if (oldPassword.equals(newPassword)){
            map.put("newPwdMsg", "不能修改成原密码！");
            return map;
        }

        //当前用户修改密码
        userMapper.updateUserPassword(user.getId(), newPassword);
        clearCache(user.getId());//密码修改后，清除缓存中的用户实例，重新添加

        return map;
    }

//    @Override
//    public int logoutUser(int id) {
//        loginTicketMapper.deleteLoginTicket(id);
//        return userMapper.deleteUser(id);
//    }

    @Override
    public User findUserByName(String username) {
        return userMapper.getUserByName(username);
    }

    //优先从缓存中获取值，
    private User getCache(int userId){
        String userRedisKey = RedisKeyUtil.getUserKey(userId);
        return (User)redisTemplate.opsForValue().get(userRedisKey);
    }

    //如果在缓存中取不到数据时，就将数据库中的值添加到缓存中
    private User initCache(int userId){
        User user = userMapper.getUserById(userId);
        String userRedisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(userRedisKey, user, 3600, TimeUnit.SECONDS);
        return user;
    }

    //数据库中的数据一旦变更，缓存中的值就无效，所以要将无效值清除
    private void clearCache(int userId){
        String userRedisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(userRedisKey);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
        User user = userMapper.getUserById(userId);

        List<GrantedAuthority> list = new ArrayList<>();

        list.add(new GrantedAuthority() {
            //自定义获取权限以及获取权限的方式
            @Override
            public String getAuthority() {
                switch (user.getType()) {
                    case 1:
                        return AUTHORITY_ADMIN;//type为1时，权限为管理员；为0时时普通用户
                    case 2:
                        return AUTHORITY_MODERATOR;
                    default:
                        return AUTHORITY_USER;
                }
            }
        });
        return list;
    }
}
